package agent.dynamic;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class ThreadCommand {

    /**
     * 打印栈信息
     */
    public static void printThreadInfo() {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        //参数一二分别为：当前的虚拟机VM是否能支持监视器和同步器，重载时的第三个参数是栈的深度（不传，默认是Int的最大值，如此，展示的栈信息最全，但性能不好）
        ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(threadMXBean.isObjectMonitorUsageSupported()
                , threadMXBean.isSynchronizerUsageSupported());
        //打印线程信息,ThreadInfo对象中包括了栈名称、方法的调用等，按需自取
        for (ThreadInfo threadInfo : threadInfos) {
            //线程信息
            StringBuilder builder = new StringBuilder();
            builder.append("name: ")
                    .append(threadInfo.getThreadName())
                    .append(" threadId: ")
                    .append(threadInfo.getThreadId())
                    .append(" threadState: ")
                    .append(threadInfo.getThreadState());
            System.out.println(builder);
            //方法调用栈
            StackTraceElement[] stackTrace = threadInfo.getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                System.out.println(stackTraceElement);
            }
        }


    }
}
